from django.views import View
from .models import Area
from django.http import JsonResponse

class ProvinceAreasView(View):
    """省级地区"""

    def get(self, request):
        try:
            # 1.查询省级数据对象
            provinces = Area.objects.filter(parent=None)
            # 2:遍历省级数据queryset对象<class 'django.db.models.query.QuerySet'>，得到<class 'apps.areas.models.Area'>
            province_list = [{'id': p.id, 'name': p.name} for p in provinces]

        except Exception as e:
              # 如果报错, 则返回错误原因:
            return JsonResponse({'code': 400,  'errmsg': '省份数据错误'})

        # 3.返回整理好的省级数据
        return JsonResponse({'code': 0, 'errmsg': 'OK', 'province_list': province_list})



# class SubAreasView(View):
#
#     def get(self, request, pk):
#
#         try:
#              # 1.查询市或区数据
#             sub_model_list = Area.objects.filter(parent=pk)
#              #  查询省份数据
#             parent_model = Area.objects.get(id=pk)
#
#             # 2.整理市或区数据
#             sub_list = []
#             for sub_model in sub_model_list:
#                 sub_list.append({'id': sub_model.id,
#                                  'name': sub_model.name})
#
#             # 父级的属性
#             sub_data = {
#                 'id': parent_model.id,  # pk
#                 'name': parent_model.name,
#                 'subs': sub_list
#             }
#
#         except Exception as e:
#             return JsonResponse({'code': 400,
#                                       'errmsg': '城市或区县数据错误'})
#
#         # 3.响应市或区数据 ok: 0
#         # 这里返回的是父级的对象，其中对象的属性subs，又存在子级的所有信息。
#         return JsonResponse({'code': 0,
#                                   'errmsg': 'OK',
#                                   'sub_data': sub_data})


class SubAreasView(View):

    def get(self, request, pk):

        try:
            # 1: 根据传入的pk值，查询子集
            son_list = Area.objects.filter(parent=pk)

            # 2：将查询结果集变成列表套字典格式
            sub_list = [{"id":p.id,"name":p.name} for p in son_list ]

            # 3:得到父级对象
            parent_model = Area.objects.get(id=pk)
        except Exception as e:
            return JsonResponse({
                "code": 400,
                "errmsg": "查询数据库错误"
            })

        sub_data = {
            "id": parent_model.id,
            "name": parent_model.name,
            "subs": sub_list,
        }

        return JsonResponse({
            "code": 0,
            "errmsg": "ok",
            "sub_data": sub_data,
        }, status=200)

